import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CookieManager extends Interceptor {
  CookieManager._privateConstructor();
  static final CookieManager _instance = CookieManager._privateConstructor();

  static get instance => _instance;

  String _cookie;

  Future initCookie() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _cookie = prefs.getString('cookie');
  }

  void _persistCookie(String newCookie) async {
    if (_cookie != newCookie) {
      _cookie = newCookie;
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('cookie', _cookie);
    }
  }

  void _clearCookie() async {
    _cookie = null;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('cookie');
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response != null) {
      if (response.statusCode == 200) {
        if (response.headers.map['set-cookie'] != null) {
          _persistCookie(response.headers.map['set-cookie'][0]);
        }
      } else if (response.statusCode == 401) {
        _clearCookie();
      }
    }
    super.onResponse(response, handler);
  }

  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) {
    options.headers['Cookie'] = _cookie;

    return super.onRequest(options, handler);
  }
}
